package com.common.supply.Utils;

import com.common.supply.config.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Component;

import java.lang.management.ManagementFactory;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 时间工具类
 *
 * @author ruoyi
 */
@Slf4j
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYYMM = "yyyyMM";

    public static String YYYY_MM_DD_SLASH = "yyyy/MM/dd";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String DD_MM_YYYY = "dd-MM-yyyy";

    public static String MM_YYYY = "MM-yyyy";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYYMMDD = "yyyyMMdd";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    public static String YYYY_MM_DD_T_HH_MM_SS_SSSXXX = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 时间间隔：日
     */
    public final static int DATE_INTERVAL_DAY = 1;
    /**
     * 时间间隔：周
     */
    public final static int DATE_INTERVAL_WEEK = 2;
    /**
     * 时间间隔：月
     */
    public final static int DATE_INTERVAL_MONTH = 3;
    /**
     * 时间间隔：年
     */
    public final static int DATE_INTERVAL_YEAR = 4;
    /**
     * 时间间隔：小时
     */
    public final static int DATE_INTERVAL_HOUR = 5;
    /**
     * 时间间隔：分钟
     */
    public final static int DATE_INTERVAL_MINUTE = 6;
    /**
     * 时间间隔：秒
     */
    public final static int DATE_INTERVAL_SECOND = 7;


    static String[] patterns = {
            "dd-MM-yyyy",
            "dd/MM/yyyy",
            "yyyy/MM/dd",
            "yyyy-MM-dd",
            "yyyy-MM-dd HH:mm:ss",
    };

    /**
     * 英文月份排序
     */
    public static List<String> MONTH_LIST = Arrays.asList("JAN", "FEB", "MAR",
            "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC");

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前时刻
     *
     * @return
     */
    public static String getCurrentClock() {
        return DateFormatUtils.format(new Date(), "HH");
    }


    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }


    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String dateTime(final Date date, String format) {
        return parseDateToStr(format, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, YYYY_MM_DD_SLASH);
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 计算两个时间差多少天
     */
    public static long getDatePoorDay(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;

        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;

        return day;
    }


    // 根据日期获取年龄31-10-1993
    public static Map<String, Integer> getAgeDetailByddmmyyyy(String date) {
        Map<String, Integer> reult = new HashMap<String, Integer>();

        //如果有空格
        int index = date.indexOf(" ");
        if (index != -1) {
            date = date.substring(0, index);
        }

        String[] data = null;
        if (date.contains("/")) {
            data = date.split("/");
        } else if (date.contains("-")) {
            data = date.split("-");
        }

        Calendar birthday = new GregorianCalendar(Integer.valueOf(data[2]), Integer.valueOf(data[1]), Integer.valueOf(data[0]));
        Calendar now = Calendar.getInstance();
        int day = now.get(Calendar.DAY_OF_MONTH) - birthday.get(Calendar.DAY_OF_MONTH);
        //月份从0开始计算，所以需要+1
        int month = now.get(Calendar.MONTH) + 1 - birthday.get(Calendar.MONTH);
        int year = now.get(Calendar.YEAR) - birthday.get(Calendar.YEAR);

        //按照减法原理，先day相减，不够向month借；然后month相减，不够向year借；最后year相减。
        if (day < 0) {
            month -= 1;
            now.add(Calendar.MONTH, -1);//得到上一个月，用来得到上个月的天数。
            day = day + now.getActualMaximum(Calendar.DAY_OF_MONTH);
        }
        if (month < 0) {
            month = (month + 12) % 12;
            year--;
        }

        reult.put("year", year);
        reult.put("month", month);
        reult.put("day", day);
        return reult;
    }

    // 根据日期获取年龄2020-05-28
    public static Map<String, Integer> getAgeDetail(String date) {
        Map<String, Integer> reult = new HashMap<String, Integer>();

        //如果有空格
        int index = date.indexOf(" ");
        if (index != -1) {
            date = date.substring(0, index);
        }

        String[] data = null;
        if (date.contains("/")) {
            data = date.split("/");
        } else if (date.contains("-")) {
            data = date.split("-");
        }

        Calendar birthday = new GregorianCalendar(Integer.valueOf(data[0]), Integer.valueOf(data[1]), Integer.valueOf(data[2]));
        Calendar now = Calendar.getInstance();
        int day = now.get(Calendar.DAY_OF_MONTH) - birthday.get(Calendar.DAY_OF_MONTH);
        //月份从0开始计算，所以需要+1
        int month = now.get(Calendar.MONTH) + 1 - birthday.get(Calendar.MONTH);
        int year = now.get(Calendar.YEAR) - birthday.get(Calendar.YEAR);

        //按照减法原理，先day相减，不够向month借；然后month相减，不够向year借；最后year相减。
        if (day < 0) {
            month -= 1;
            now.add(Calendar.MONTH, -1);//得到上一个月，用来得到上个月的天数。
            day = day + now.getActualMaximum(Calendar.DAY_OF_MONTH);
        }
        if (month < 0) {
            month = (month + 12) % 12;
            year--;
        }

        reult.put("year", year);
        reult.put("month", month);
        reult.put("day", day);
        return reult;
    }

    public static String getFewDay(int fewDay) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, fewDay);
        return DateFormatUtils.format(calendar.getTime(), YYYY_MM_DD_SLASH);
    }

    /**
     * 获取时间差[前面时间和比较时间比,小于比较时间返回负数]
     *
     * @param level   返回时间等级(1:返回天;2:返回天-小时;3:返回天-小时-分4:返回天-小时-分-秒;5:只返回相差时【cyh】)
     * @param date    时间
     * @param compare 比较的时间
     * @return 时间差(保留两位小数点, 小数点以后两位四舍五入)
     * @author sunju
     * @creationDate. 2010-9-1 下午04:36:07
     */
    public static String getDateBetween(Integer level, Date date, Date compare) {
        if (date == null || compare == null) {
            return null;
        }
        long s = new BigDecimal(getDateDiff(DATE_INTERVAL_SECOND, date, compare)).setScale(2, BigDecimal.ROUND_HALF_UP).longValue();
        int ss = 1;
        int mi = ss * 60;
        int hh = mi * 60;
        int dd = hh * 24;

        long day = s / dd;
        long hour = (s - day * dd) / hh;
        long minute = (s - day * dd - hour * hh) / mi;
        long second = (s - day * dd - hour * hh - minute * mi) / ss;
        String flag = (day < 0 || hour < 0 || minute < 0 || second < 0) ? "-" : "";
        day = Math.abs(day);
        hour = Math.abs(hour);
        minute = Math.abs(minute);
        second = Math.abs(second);
        StringBuilder result = new StringBuilder(flag);
        switch (level) {
            case 1:
                if (day != 0) {
                    result.append(day).append("天");
                }
                break;
            case 2:
                if (day != 0) {
                    result.append(day).append("天");
                }
                if (hour != 0) {
                    result.append(hour).append("小时");
                }
                break;
            case 3:
                if (day != 0) {
                    result.append(day).append("天");
                }
                if (hour != 0) {
                    result.append(hour).append("小时");
                }
                if (minute != 0) {
                    result.append(minute).append("分");
                }
                break;
            case 4:
                if (day != 0) {
                    result.append(day).append("天");
                }
                if (hour != 0) {
                    result.append(hour).append("小时");
                }
                if (minute != 0) {
                    result.append(minute).append("分");
                }
                if (second != 0) {
                    result.append(second).append("秒");
                }
                break;
            case 5:
                result.append(hour);
            default:
                break;
        }
        return result.toString();
    }

    /**
     * 两个时间时间差[前面时间和比较时间比,小于比较时间返回负数]
     *
     * @param interval 比较项，可以是天数、月份、年数、时间、分钟、秒
     * @param date     时间
     * @param compare  比较的时间
     * @return 时间差(保留两位小数点, 小数点以后两位四舍五入)
     * @author sunju
     * @creationDate. 2010-8-27 下午05:26:13
     */
    public static double getDateDiff(int interval, Date date, Date compare) {
        if (date == null || compare == null) {
            return 0;
        }
        double result = 0;
        double time = 0;
        Calendar calendar = null;
        switch (interval) {
            case DATE_INTERVAL_DAY:
                time = date.getTime() - compare.getTime();
                result = time / 1000d / 60d / 60d / 24d;
                break;
            case DATE_INTERVAL_HOUR:
                time = date.getTime() - compare.getTime();
                result = time / 1000d / 60d / 60d;
                break;
            case DATE_INTERVAL_MINUTE:
                time = date.getTime() / 1000d / 60d;
                result = time - compare.getTime() / 1000d / 60d;
                break;
            case DATE_INTERVAL_MONTH:
                calendar = Calendar.getInstance();
                calendar.setTime(date);
                time = calendar.get(Calendar.YEAR) * 12d;
                calendar.setTime(compare);
                time -= calendar.get(Calendar.YEAR) * 12d;
                calendar.setTime(date);
                time += calendar.get(Calendar.MONTH);
                calendar.setTime(compare);
                result = time - calendar.get(Calendar.MONTH);
                break;
            case DATE_INTERVAL_SECOND:
                time = date.getTime() - compare.getTime();
                result = time / 1000d;
                break;
            case DATE_INTERVAL_WEEK:
                calendar = Calendar.getInstance();
                calendar.setTime(date);
                time = calendar.get(Calendar.YEAR) * 52d;
                calendar.setTime(compare);
                time -= calendar.get(Calendar.YEAR) * 52d;
                calendar.setTime(date);
                time += calendar.get(Calendar.WEEK_OF_YEAR);
                calendar.setTime(compare);
                result = time - calendar.get(Calendar.WEEK_OF_YEAR);
                break;
            case DATE_INTERVAL_YEAR:
                calendar = Calendar.getInstance();
                calendar.setTime(date);
                time = calendar.get(Calendar.YEAR);
                calendar.setTime(compare);
                result = time - (double) calendar.get(Calendar.YEAR);
                break;
            default:
                break;
        }
        return new BigDecimal(result).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * 日期格式转换yyyy-MM-dd'T'HH:mm:ss.SSSXXX  (yyyy-MM-dd'T'HH:mm:ss.SSSZ) TO  yyyy-MM-dd HH:mm:ss
     * 2020-04-09T23:00:00.000+08:00 TO 2020-04-09 23:00:00
     *
     * @throws ParseException
     */
    public static String dealDateFormat(String oldDateStr) throws ParseException {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");  //yyyy-MM-dd'T'HH:mm:ss.SSSZ
        Date date = df.parse(oldDateStr);
        SimpleDateFormat df1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
        Date date1 = df1.parse(date.toString());
        DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df2.format(date1);
    }

    /**
     * 日期格式转换 yyyy-MM-dd HH:mm:ss  TO yyyy-MM-dd'T'HH:mm:ss.SSSXXX  (yyyy-MM-dd'T'HH:mm:ss.SSSZ)
     * 2020-04-09 23:00:00 TO 2020-04-09T23:00:00.000+08:00
     *
     * @throws ParseException
     */
    public static String dealDateFormatReverse(String oldDateStr) throws ParseException {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
        DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1 = df2.parse(oldDateStr);
        return df.format(date1);
    }

    /**
     * 日期多类型转换统一类型 ：DD-MM-YYYY
     *
     * @param daeStr
     * @return
     */
    public static String multipleParse(String daeStr) {
        daeStr = daeStr.trim();
        //DD-MMM-YYY格式
        boolean matches = daeStr.matches("\\d{2}-[A-Za-z]{3}-\\d{4}");
        if (matches) {
            String[] split = daeStr.split("-");
            split[1] = changeStringToNumber(split[1]);
            String str = "";
            for (int i = 0; i < split.length; i++) {
                str = str + split[i];
                if (i != split.length - 1) {
                    str = str + "-";
                }
            }
            return str;
        }
        SimpleDateFormat df = new SimpleDateFormat();
        for (String pattern : patterns) {
            df.applyPattern(pattern);
            //设置解析日期格式是否严格解析日期
            df.setLenient(false);
            ParsePosition pos = new ParsePosition(0);
            Date date = df.parse(daeStr, pos);
            if (date != null) {
                return dateTime(date, parseDateToStr(MM_YYYY, date));
            }
        }
        return null;
    }

    /**
     * MM-yyyy
     * 根据生日获取年龄
     *
     * @param birth
     * @return
     * @throws ParseException
     */
    public static int getAgeByBirth(String birth) {
        SimpleDateFormat sdf = new SimpleDateFormat(MM_YYYY);
        Date birthDay = null;
        try {
            birthDay = sdf.parse(birth);
        } catch (ParseException e) {
            log.error("根据生日获取年龄 error", e);
            return 0;
        }

        int age = 0;
        Calendar cal = Calendar.getInstance();
        //出生日期晚于当前时间，无法计算
        if (cal.before(birthDay)) {
            throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        //计算整岁数
        age = yearNow - yearBirth;
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                ////当前日期在生日之前，年龄减一
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;
                }
            } else {
                //当前月份在生日之前，年龄减一
                age--;
            }
        }
        return age;
    }


    public static String changeStringToNumber(String releaseVersion) {
        if (null == releaseVersion) {
            throw new IllegalArgumentException("ReleaseVersion cannot be null");
        }
        for (int i = 0; i < MONTH_LIST.size(); i++) {
            if (releaseVersion.toUpperCase().startsWith(MONTH_LIST.get(i))) {
                int m = i + 1;
                if (i < 9) {
                    return "0" + m;
                }
                return m + "";
            }
        }
        return -1 + "";
    }

    /**
     * 计算两个日期之间相差的天数
     *
     * @param smdate 较小的时间
     * @param bdate  较大的时间
     * @return 相差天数
     * @throws ParseException
     */
    public static int daysBetween(Date smdate, Date bdate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            smdate = sdf.parse(sdf.format(smdate));
            bdate = sdf.parse(sdf.format(bdate));
        } catch (ParseException e) {
            throw new BusinessException("abnormal format！");
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));
    }


    public static int getDaysOfTwoDate(Date fstDate, Date sndDate) throws ParseException {
        Date date1st = parse(formatDate(fstDate, "yyyy-MM-dd"), "yyyy-MM-dd");
        Date date2nd = parse(formatDate(sndDate, "yyyy-MM-dd"), "yyyy-MM-dd");
        boolean sign = date1st.before(date2nd);
        Date date1 = sign ? date1st : date2nd;
        Date date2 = sign ? date2nd : date1st;
        Calendar calendar = Calendar.getInstance();
        int days = 0;
        for (; date1.before(date2); date1 = calendar.getTime()) {
            days++;
            calendar.setTime(date1);
            calendar.add(5, 1);
        }

        return sign ? days : -days;
    }

    /**
     * 日期格式化 转String
     *
     * @param date
     * @param pattern
     * @return
     */
    public static String formatDate(Date date, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        if (date == null) {
            return null;
        }
        return sdf.format(date);

    }

    public static Date parse(String date, String pattern) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.parse(date);
    }

    public static Date dateFormatConversion(String pattern, String time) throws ParseException {
        if (time == null || time.equals("")) {
            return new Date();
        }
        Date a = new SimpleDateFormat(pattern, Locale.US).parse(time);
        if (a.getHours() == 12) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(a);
            calendar.add(Calendar.HOUR, -12);
            a = calendar.getTime();
        }
        if (time.contains("PM") && a.getHours() != 12) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(a);
            calendar.add(Calendar.HOUR, 12);
            a = calendar.getTime();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(a);
        calendar.add(Calendar.HOUR, -1);
        a = calendar.getTime();
        return a;
    }

    public static Date parseUTCText(String text) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        if (text.indexOf(".") > -1) {
            String prefix = text.substring(0, text.indexOf("."));
            String suffix = text.substring(text.indexOf("."));
            if (suffix.length() >= 5) {
                suffix = suffix.substring(0, 4) + "Z";
            } else {
                int len = 5 - suffix.length();
                String temp = "";
                temp += suffix.substring(0, suffix.length() - 1);
                for (int i = 0; i < len; i++) {
                    temp += "0";
                }
                suffix = temp + "Z";
            }
            text = prefix + suffix;
        } else {
            text = text.substring(0, text.length() - 1) + ".000Z";
        }
        Date date = sdf.parse(text);
        return date;
    }

    public static boolean isToday(Date date) throws ParseException {
        Calendar c1 = Calendar.getInstance();
        c1.setTime(date);
        int year1 = c1.get(Calendar.YEAR);
        int month1 = c1.get(Calendar.MONTH) + 1;
        int day1 = c1.get(Calendar.DAY_OF_MONTH);
        Calendar c2 = Calendar.getInstance();
        c2.setTime(new Date());
        int year2 = c2.get(Calendar.YEAR);
        int month2 = c2.get(Calendar.MONTH) + 1;
        int day2 = c2.get(Calendar.DAY_OF_MONTH);
        if (year1 == year2 && month1 == month2 && day1 == day2) {
            return true;
        }
        return false;

    }


    /**
     * 时间是否是近 n 个月
     *
     * @param n    月
     * @param date 比较时间 (09/01/2021)
     * @return true 则是，反之
     */
    public static boolean checkNearMonth(int n, String date) {
        LocalDateTime time = timeFormat(date);
        if (time == null) {
            return false;
        }
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime zeroTime = LocalDateTime.of(now.toLocalDate(), LocalTime.MIN);
        return time.compareTo(zeroTime.minusMonths(n)) >= 0 && time.compareTo(zeroTime) <= 0;
    }

    /**
     * 比较时间是否大于当前时间 (09/01/2021)
     *
     * @param date 时间字符串
     * @return true 则大于当前时间或者为空
     */
    public static boolean checkTimeUpNow(String date) {
        if (Func.isEmpty(date)) {
            return true;
        }
        LocalDateTime time = timeFormat(date);
        if (time == null) {
            return true;
        }
        return time.compareTo(LocalDateTime.now()) > 0;
    }

    /**
     * 特殊时间格式化 (09/01/2021)
     *
     * @param date 时间字符串
     * @return 时间
     */
    public static LocalDateTime timeFormat(String date) {
        if (Func.isEmpty(date)) {
            return null;
        }
        if (date.trim().equals("#")) {
            return null;
        }
        date = date.trim();
        String[] timeSplit = date.split("/");
//        时间格式效验
        if (timeSplit.length != 3) {
            return null;
        }
//        时间格式补全成 00 模式
        if (timeSplit[0].length() < 2) {
            timeSplit[0] = "0" + timeSplit[0];
        }
        if (timeSplit[1].length() < 2) {
            timeSplit[1] = "0" + timeSplit[1];
        }

        date = timeSplit[0] + "/" + timeSplit[1] + "/" + timeSplit[2];

        date += " 00:00:00";
        LocalDateTime time = null;
        try {
            time = LocalDateTime.parse(date, DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"));
        } catch (Exception e) {
            return null;
        }
        return time;
    }

    /**
     * 获取时间月份差
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     */
    public static int getMonthInterval(LocalDateTime endTime, LocalDateTime startTime) {
        if (startTime == null || endTime == null) {
            return -1;
        }
        return (endTime.getYear() - startTime.getYear()) * 12 + (endTime.getMonthValue() - startTime.getMonthValue());
    }

    /**
     * 判断时间是否在间隔内
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param max       间隔小于等于 max
     * @param min       间隔大于等于 min
     * @return true 是
     */
    public static boolean getNearMonth(LocalDateTime startTime, LocalDateTime endTime, Integer max, Integer min) {
        boolean more = true;
        boolean low = true;
        if (max == null && min == null) {
            return false;
        }
        if (max != null) {
            low = getMonthInterval(startTime, endTime) <= max;
        }
        if (min != null) {
            more = getMonthInterval(startTime, endTime) >= min;
        }
        return more && low;
    }


    /**
     * 获取天数差
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     */
    public static long getDayInterval(LocalDateTime endTime, LocalDateTime startTime) {
        if (startTime == null || endTime == null) {
            return -1;
        }
        Duration duration = Duration.between(startTime, endTime);
        return duration.toDays();
    }

    /**
     * 判断时间是否在间隔内
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param max       间隔小于等于 max
     * @param min       间隔大于等于 min
     * @return true 是
     */
    public static boolean getNearDay(LocalDateTime startTime, LocalDateTime endTime, Integer max, Integer min) {
        boolean more = true;
        boolean low = true;
        if (max == null && min == null) {
            return false;
        }
        if (max != null) {
            low = getDayInterval(startTime, endTime) <= max;
        }
        if (min != null) {
            more = getDayInterval(startTime, endTime) >= min;
        }
        return more && low;
    }

    public static LocalDateTime getTimeFromString(String time) {
        try {
            return LocalDateTime.parse(time, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        } catch (Exception e) {
            return null;
        }
    }

    public static LocalDateTime getTimeFromDate(Date time) {
        if (time == null) {
            return null;
        }
        return time.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }


    /**
     * 增加指定天数
     *
     * @param date
     * @param amount
     * @return
     */
    public static Date addDays(Date date, int amount) {
        GregorianCalendar gregorianCalendar = new GregorianCalendar();
        gregorianCalendar.setTime(date);
        gregorianCalendar.add(GregorianCalendar.DATE, amount);
        return gregorianCalendar.getTime();
    }

    /**
     * 2个时间比较
     * @param leftTimeParam 左边
     * @param rightTimeParam 右边
     * @param pattern yyyy-MM-dd HH:mm:ss、yyyy-MM-dd HH:mm、yyyy-MM-dd
     * 等于0，leftTimeParam=rightTimeParam；
     * 等于 1 ，leftTimeParam>rightTimeParam ;
     * //等于-1，leftTimeParam<rightTimeParam。
     * @return
     */
    public  static int compareTimes(String leftTimeParam,String rightTimeParam,String pattern){
        LocalDateTime leftTime = LocalDateTime.parse(leftTimeParam, DateTimeFormatter.ofPattern(pattern));
        LocalDateTime rightTime =  LocalDateTime.parse(rightTimeParam, DateTimeFormatter.ofPattern(pattern));
        return leftTime.compareTo(rightTime);
    }
//
//    public static void main(String[] args) {
//        int a =compareTimes(dateTimeNow("yyyy-MM-dd HH:mm"),"2022-04-09 23:55","yyyy-MM-dd HH:mm");
//        System.out.println(a);
//    }

}
